import {
  provide,
  reactive,
  getCurrentInstance
} from "vue";
import { debounce } from "../utils";
const sortChildren = debounce(
  (parent, publicChildren, internalChildren) => {
    const vnodes = parent.proxy.$children;
    internalChildren.sort(
      (a, b) => vnodes.indexOf(a.exposeProxy) - vnodes.indexOf(b.exposeProxy)
    );
    const orderedPublicChildren = internalChildren.map((item) => item.proxy);
    publicChildren.sort((a, b) => {
      const indexA = orderedPublicChildren.indexOf(a);
      const indexB = orderedPublicChildren.indexOf(b);
      return indexA - indexB;
    });
  },
  1e3 / 60
);
function useChildren(key) {
  const publicChildren = reactive([]);
  const internalChildren = reactive([]);
  const parent = getCurrentInstance();
  const linkChildren = (value) => {
    const link = (child) => {
      if (child.proxy) {
        internalChildren.push(child);
        publicChildren.push(child.proxy);
        sortChildren(parent, publicChildren, internalChildren);
      }
    };
    const unlink = (child) => {
      const index = internalChildren.indexOf(child);
      publicChildren.splice(index, 1);
      internalChildren.splice(index, 1);
    };
    provide(
      key,
      Object.assign(
        {
          link,
          unlink,
          children: publicChildren,
          internalChildren
        },
        value
      )
    );
  };
  return {
    children: publicChildren,
    linkChildren
  };
}
export {
  sortChildren,
  useChildren
};
